package com.dy.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dy.mapper.DyPermissionMapper;
import com.dy.mapper.DyRolesMapper;
import com.dy.mapper.DyUserMapper;
import com.dy.pojo.entity.DyUserEntity;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @ClassName:
 * @Author: 仄言in
 * @Desctiption: (描述)
 * @Date: 2021/6/1 17:50
 * @Version 1.0 (版本)
 */
public class MyRealm extends AuthorizingRealm {
    @Autowired
    private DyUserMapper dyUserMapper;
    @Autowired
    private DyRolesMapper dyRolesMapper;
    @Autowired
    private DyPermissionMapper dyPermissionMapper;
    @Override
    public String getName() {
        return "myRealm";
    }

    /**
     * 授权
     * @param principalCollection
     * @return SimpleAuthorizationInfo
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        DyUserEntity user = (DyUserEntity) principalCollection.iterator().next();
        //根据用户名返回角色和权限
        Set<String> rolesName = dyRolesMapper.getRoles(user.getUsername());
        Set<String> permissionName = dyPermissionMapper.getPermission(user.getUsername());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(rolesName);
        info.setStringPermissions(permissionName);
        return info;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return AuthenticationInfo
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token= (UsernamePasswordToken) authenticationToken;
        String username=token.getUsername();
        QueryWrapper<DyUserEntity> queryWrapper = new QueryWrapper<>();
        DyUserEntity selectOne = dyUserMapper.selectOne(queryWrapper.eq("username", username));
        if (selectOne == null) {
            return null;
        }
        AuthenticationInfo info = new SimpleAuthenticationInfo(selectOne, selectOne.getPassword(),ByteSource.Util.bytes(selectOne.getSalt()),getName());
        return info;
    }
}
